package com.example.downloaddemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.example.downloaddemo.downloader.DataWatcher;
import com.example.downloaddemo.downloader.DownloadEntry;
import com.example.downloaddemo.downloader.DownloadManager;

import java.util.ArrayList;
import java.util.List;

public class DemoActivity2 extends AppCompatActivity implements View.OnClickListener {

    private DownloadManager mDownloadManager;
    private DataWatcher watcher = new DataWatcher() {
        @Override
        public void notifyUpdate(DownloadEntry data) {
            if (data.status == DownloadEntry.DownloadStatus.cancel) {
                downloadEntry = null;
            }

            int index = mDownloadEntrys.indexOf(data);
            if (index!=-1){
                mDownloadEntrys.remove(index);
                mDownloadEntrys.add(index,data);
                listAdapter.notifyDataSetChanged();
            }


            Log.e("TAG", "============notifyUpdate=========");
        }
    };
    private TextView tv_down, tv_pause;
    private DownloadEntry downloadEntry;
    private ListView list_view;
    private List<DownloadEntry> mDownloadEntrys = new ArrayList<>();
    private ListAdapter listAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo2);
        mDownloadManager = DownloadManager.getInstance(this);
        tv_down = findViewById(R.id.tv_down);
        tv_pause = findViewById(R.id.tv_pause);
        list_view = findViewById(R.id.list_view);
        tv_down.setOnClickListener(this);
        tv_pause.setOnClickListener(this);
        for (int i = 0; i < 50; i++) {
            mDownloadEntrys.add(new DownloadEntry(i, "下载" + i));
        }
        listAdapter = new ListAdapter(this,mDownloadEntrys,R.layout.item_list_view);
        list_view.setAdapter(listAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDownloadManager.addObserver(watcher);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDownloadManager.removeObserver(watcher);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_down:
                downloadEntry = new DownloadEntry();
                downloadEntry.setId(1);
                mDownloadManager.add(downloadEntry);
                break;
            case R.id.tv_pause:
                mDownloadManager.cancel(downloadEntry);
                break;
        }
    }
}